<?
class Handler {
	/***********************************
	 *           PASSWORDS
	 ***********************************/
	private $mysql_password = "****";
	private $twitter_password = "****";
	/***********************************
	 *         DEFAULT VALUES
	 ***********************************/
	private $default_rate_limit = 3600;
	private $default_time_out = 300;
	/***********************************
	 *      CONFIGURATION FILES
	 ***********************************/
	private $xml_conf = "conf/conf.xml";
	//private $xml_conf = "conf/conf_netsons.xml";
	private $xml_parser = "conf/parser.xml";
	private $xml_error = "conf/error.xml";
	
	
	
	/************************************
	 *  NO NEED TO MODIFY ANYTHING ELSE
	 * Check your 'conf.xml' for editing
	 * any configuration detail you want
	 ************************************/
	private $conn;
	private $twitwords;
	private $twitter;
	private $parser;
	private $config;
	private $error;
	private $path = "../";
	
	
	/**
	* Load all configuration details in XML
	*/
	public function __construct($path = NULL) {
		//error_reporting(0);
		if($path!=NULL) $this->path = $path;
		$this->config = simplexml_load_file($this->path.$this->xml_conf);
		$this->parser = simplexml_load_file($this->path.$this->xml_parser);
		if($this->config && $this->parser) {
			$this->database = $this->config->database;
			$this->twitwords = $this->config->twitwords;
			$this->twitter = $this->config->twitter;
		}
		return ($this->config && $this->parser);
	}
	
	/**
	 * Start a connection with MySQL
	 */
	public function openDB($schema = NULL) {
		$dbhost = sprintf("%s:%s", $this->config->database->host, $this->database->port);
		$this->conn = mysql_connect($dbhost, $this->database->username, $this->mysql_password);
		if($this->conn) {
			if($schema!=NULL) $this->database->schema = $schema;
			mysql_select_db($this->database->schema);
		}
		return $this->conn;
	}
	
	/**
	 * Select a database to use
	 */
	public function selectDB($schema) {
		return mysql_select_db($this->schema);
	}
	
	/**
	 * Delete all data from the specified table
	 */
	public function truncateDB($table) {
		$query = "TRUNCATE TABLE $table";
		return mysql_query($query);
	}
	
	/**
	 * Close the connection with MySQL
	 */
	public function closeDB() {
		mysql_close($this->conn);
	}
	
	/**
	 * All getters of the configuration details
	 */
	
	public function getTwitterUser() {
		return $this->twitter->user;
	}
	
	public function getTwitterPassword() {
		return $this->twitter_password;
	}
	
	public function getTwitterRateLimit() {
		switch($this->twitter->rate_limit['unit']) {
			case "sec":
				return $this->twitter->rate_limit;
			case "min":
				return 60*$this->twitter->rate_limit;
			default:
				return $this->default_rate_limit;
		}
	}
	
	public function getGMT() {
		return $this->twitwords->gmt;
	}
	
	public function getDateFormat() {
		return $this->twitwords->date_format_us;
	}
	
	public function getTagsInRSS() {
		return $this->twitwords->tags_in_rss;
	}
	
	public function getTagsPerPage() {
		return $this->twitwords->tags_per_page;
	}
	
	public function getUsersPerPage() {
		return $this->twitwords->users_per_page;
	}
	
	public function getBaseURL() {
		return $this->twitwords->base_url;
	}
	
	public function getMaxPriority() {
		return $this->twitwords->max_priority;
	}
	
	public function getDefaultPriority() {
		return $this->twitwords->default_priority;
	}
	
	public function getCredits() {
		return $this->twitwords->credits;
	}
	
	public function useAutocompleter() {
		return strtolower($this->twitwords->autocompleter)=="true";
	}
	
	public function getAutocompleterResults() {
		return $this->twitwords->autocompleter_results;
	}
	
	public function displayProgressBar() {
		return strtolower($this->twitwords->progress_bar)=="true";
	}
	
	public function getTitle() {
		//echo $this->twitwords->title;
		return $this->twitwords->title;
	}
	
	public function getSubtitle() {
		//echo $this->twitwords->sub_title;
		return $this->twitwords->sub_title;
	}
	
	public function getAnnotation() {
		return $this->twitwords->annotation;
		//return $this->twitwords->annotation.$this->twitter->user;
	}
	
	public function getTagSeparator() {
		return $this->twitwords->tag_separator;
	}
	
	public function getTimeOut() {
		$value = $this->twitwords->time_out;
		switch($this->twitwords->time_out['unit']) {
			case "sec":
				return $value;
			case "min":
				return 60*$value;
			default:
				return $this->default_time_out;
		}
	}
	
	public function getLastTimestamp() {
		return $this->parser->last_timestamp;
	}
	
	public function getLastExceedingRequest() {
		return $this->parser->last_exceeding_request;
	}
	
	public function getLastStatus() {
		return $this->parser->last_status;
	}
	
	/**
	 * Save to XML last parsing timestamp and status id
	 */
	public function setLastParsing($time, $status = NULL) {
		$file = file_get_contents($this->path.$this->xml_parser);
		//$this->parser->last_timestamp = $time;
		$file = preg_replace("/<last_timestamp>([0-9]+)/i", "<last_timestamp>$time", $file);
		if($status!=NULL) {
			//$this->parser->last_status = $status;
			$file = preg_replace("/<last_status>([0-9]+)/i", "<last_status>$status", $file);
		}
		/* DEBUG */
		//echo $this->parser->asXML();
		return file_put_contents($this->path.$this->xml_parser, $file);
	}
	
	/**
	 * Save to XML last exceeding request timestamp
	 */
	public function setLastExceedingRequest($time) {
		//$file = fopen($this->path.$this->xml_parser, "w");
		$file = file_get_contents($this->path.$this->xml_parser);
		//$this->parser->last_exceeding_request = $time;
		$file = preg_replace("/<last_exceeding_request>([0-9]+)/i", "<last_exceeding_request>$time", $file);
		//return fwrite($file, $this->parser->asXML());
		return file_put_contents($this->path.$this->xml_parser, $file);
	}
	
	/**
	 * Fetch XML error file and return the specific error message
	 */
	public function getErrorMessage($error) {
		$this->error = simplexml_load_file($this->path.$this->xml_error);
		if($this->error) {
			//echo "A";
			$error = $this->error->xpath("error[type='$error']/message");
			//echo print_r($error);
			return $error[0];
		} else {
			//echo "B";
			return NULL;
		}
	}
	
	/**
	 * Check whether the specified image url is still valid 
	 */
	public function hasHTTPError($url) {
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, $url);
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl_handle, CURLOPT_FAILONERROR, true);
		curl_exec($curl_handle);
		return (curl_errno($curl_handle)>0);
	}
	
	/**
	 * Compute the gap between the timestamps passed as arguments
	 */
	public function deltaToTime($now, $date) {
		//echo date($hd->getDateFormat(), strtotime('2008-04-20 15:07:29'));
		$out = "";
		//$gmt = 3600*(int)$this->getGMT();
		//$delta = $now-$date+$gmt;
		$delta = $now-$date;
		//echo $delta;
		if($delta/86400>8) {
			// more than 8 days ago... let's print out the date normally
			$out .= date($this->getDateFormat(), $date);
		} else {
			if($delta/86400>6) {
				$out = "Around a week ago";
			} else if(($day = $delta/86400)>1) {
				// more than one day ago
				if($day>1.5) {
					$out .= floor($day)." day";
					if(floor($day)>1) {
						$out .= "s";
					}
					// if more than one day ago, print only the hours
					$delta = $delta%86400;
					if(($hour = floor($delta/3600))>=1) {
						$out .= " and $hour hour";
						if($hour>1) {
							$out .= "s";
						}
					}
					$out .= " ago";
				} else {
					$out .= "Yesterday";
				}
			} else {
				// less than one day ago... print hours and minutes
				if(($hour = floor($delta/3600))>=1) {
					$out .= "$hour hour";
					if($hour>1) {
						$out .= "s";
					}
					$delta = $delta%3600;
					if(($minute = floor($delta/60))>=1) {
						$out .= " and $minute minute";
						if($minute>1) {
							$out .= "s";
						}
					}
					$out .= " ago";
				} else {
					// less than an hour ago... print minutes and seconds
					if(($minute = floor($delta/60))>=1) {
						$out .= "$minute minute";
						if($minute>1) {
							$out .= "s";
						}
					}
					if(($second = $delta%60)!=0) {
						$out .= " and $second seconds";
					}
					$out .= " ago";
				}
			}
		}
		return $out;
	}
	
}
?>